package com.bjpowernode.singleton.attack;

import java.io.*;

/**
 * @ClassName Singleton01
 *
 * @Author Cat
 */
public final class SingletonAttack01 implements Serializable {

    //类变量，在类加载的时候就会初始化，在多线程下也不会出现初始化两次的情况
    private static SingletonAttack01 instance = new SingletonAttack01();

    private SingletonAttack01() {
        if (instance != null) {
            throw new RuntimeException("哎呀，不能通过反射创建单例对象.");
        }
    }

    public static SingletonAttack01 getInstance() {
        return instance;
    }

    public Object readResolve() {
        return instance;
    }

    public static void main(String[] args) throws Exception{
        /*SingletonAttack01 instance1 = SingletonAttack01.getInstance();
        System.out.println(instance1);

        Constructor<SingletonAttack01> constructor = SingletonAttack01.class.getDeclaredConstructor();
        constructor.setAccessible(true);//对私有构造器开放权限

        SingletonAttack01 newInstance1 = constructor.newInstance();
        System.out.println(newInstance1);

        SingletonAttack01 newInstance2 = constructor.newInstance();
        System.out.println(newInstance2);*/


        //序列化
        SingletonAttack01 instance1 = SingletonAttack01.getInstance();
        System.out.println(instance1);

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("SerSingleton.obj"));
        oos.writeObject(instance1);
        oos.flush();
        oos.close();

        //反序列化
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("SerSingleton.obj"));
        SingletonAttack01 rs01 = (SingletonAttack01)ois.readObject();
        ois.close();
        System.out.println(rs01);

    }
}